import 'dart:async';
import 'dart:io';

import 'package:app_map/app_map.dart';
import 'package:app_network/app_network.dart';
import 'package:app_images_action_image_pickers/app_images_action_image_pickers.dart';
import 'package:app_info_choose_kit/app_info_choose_kit.dart';
import 'package:bruno/bruno.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_effect/flutter_effect.dart';
import 'package:flutter_theme_helper/flutter_theme_helper.dart';
import 'package:tsdemo/common/event.dart';
import 'package:tsdemo/common/event_bus.dart';
import 'package:tsdemo/http/Network/UrlPath.dart';
import 'package:tsdemo/module/tsdemo/api/crowd_api.dart';
import 'package:tsdemo/module/tsdemo/widget/relation_user_modal.dart';
import 'package:tsdemo/module/tsdemo/tsdemo_create/model/tsdemo_template_model.dart';
import 'package:tsdemo/module/tsdemo/tsdemo_create/util/tsdemo_publish_info_util.dart';
import 'package:tsdemo/module/tsdemo/tsdemo_create/widget/tsdemo_verify_widget.dart';
import 'package:tsdemo/module/tsdemo/tsdemo_create/tsdemo_publish_cache_util.dart';
import 'package:tsdemo/module/tsdemo/tsdemo_create/tsdemo_publish_manager.dart';
import 'package:tsdemo/module/tsdemo/tsdemo_create/tsdemo_publish_notifier.dart';
import 'package:tsdemo/module/tsdemo/tsdemo_detail/model/relation.dart';
import 'package:tsdemo/module/tsdemo/tsdemo_detail/model/relation_user.dart';

import 'package:tsdemo/route/route_manager.dart';
import 'package:app_service_user/app_service_user.dart';
import 'package:tsdemo/common/utils.dart';

import 'package:tsdemo/ui/class/tsdemohouse/model/show_account_info.dart';
import 'package:tsdemo/module/tsdemo/tsdemo_detail/model/tsdemo_detail_model.dart';
import 'package:tsdemo/ui/class/tsdemohouse/newWishHouse/pop_select_power_page.dart';

import './widget/good_choose_widget.dart';

import '../util/tsdemo_goods_util.dart';

class WishPublishPage extends BJHBasePage {
  bool isUpdateBusiness;
  WishDetailModel tsdemoDetailModel;

  WishPublishPage({
    Key key,
    this.isUpdateBusiness = false,
    this.tsdemoDetailModel,
  }) : super(key: key) {
    // do something
  }

  WishPublishPage.fromTemplatePage({
    Key key,
    this.isUpdateBusiness = false,
    WishTemplateModel templateModel,
  }) : super(key: key) {
    tsdemoDetailModel =
        WishDetailModel.fromTemplateJson(templateModel.toJson());
  }

  WishPublishPage.fromOtherUser({
    Key key,
    List<Items> selectGoodsList,
  }) : super(key: key) {
    isUpdateBusiness = false;
    tsdemoDetailModel = WishDetailModel(); // 必须初始化
    tsdemoDetailModel.items = selectGoodsList; // 暂时只平移代码，不修改(原本可能有问题)
  }

  @override
  _WishPublishPageState createState() => _WishPublishPageState();
}

class _WishPublishPageState<T extends UserBaseBean>
    extends BJHBasePageState<WishPublishPage>
    with SingleTickerProviderStateMixin, WidgetsBindingObserver {
  bool _isUpdateBusiness;

  // 监听
  StreamSubscription _tsdemoPowerEvent;

  // 内容详情
  WishDetailModel _tsdemoDetailModel;

  PublishModel get _publishModel => WishPublishManager().publishModel;

  String get _tsdemoId => _publishModel.tsdemoId;

  String get _tsdemoTemplateId => _publishModel.tsdemoTemplateId;

  String get _publishTitle => _publishModel.publishTitle;

  String get _publishDescribe => _publishModel.publishDescribe;

  List<String> get _messageAtUserIds => _publishModel.messageAtUserIds;

  DateChooseBean get _dateChooseBean => _publishModel.dateChooseBean;

  String get _dateChooseString => _publishModel.dateChooseString;

  int get _showType => _publishModel.showType;

  List<ShowAccountInfo> get _selectUsers => _publishModel.selectUsers;

  List<SelectedTagInfo> get _selectedTagInfos => _publishModel.selectedTagInfos;

  List<AppImageChooseBean> get _imageChooseModels =>
      _publishModel.imageChooseModels;

  ImageChooseBean get _coverImageChooseModel =>
      _publishModel.coverImageChooseModel;

  VoiceBean get _uploadVoiceBean => _publishModel.uploadVoiceBean;

  LocationBean get _locationBean => _publishModel.locationBean;

  AddressListEntity get _addressModel => _publishModel.addressModel;

  List<Items> get _showGoodsModels => _publishModel.showGoodsModels;

  List<Items> get _hideGoodsModels => _publishModel.hideGoodsModels;

  bool get _isCrowd => _publishModel.isCrowd;

  int get _crowdNum => _publishModel.crowdNum;

  bool get _hasWishCrowd => _publishModel.hasWishCrowd;

  bool get _hasEditWishGoods => _publishModel.hasEditWishGoods;

  String get _tsdemoType => _publishModel.tsdemoType;

  // 文本
  TextEditingController _publishTitleController = TextEditingController();

  // 标签(目前需求是只能单选一个标签)
  List<TagModel> _allTagModels = [];
  List<String> tsdemoTags = ['99'];
  var tagColor = "ff937E59";
  var tagColorOpacity = "90937E59";

  // 上一次搜索的关键字
  String _keyword = '';

  // 上一次搜索的频道tabIndex
  int _tabIndex = 0;
  FocusNode _mainTitleFocusNode;

  // 寄语的输入框
  TextEditingController _controller;
  final FocusNode _focusNode = FocusNode();

  double leftRightPadding = 0; // cell 内容的左右间距(未设置时候，默认20)

  List<RelationUser> _relationUsers = [];
  bool _isOpenAtDialog = false;

  final ScrollController _customScrollcontroller = ScrollController();

  @override
  bool get wantKeepAlive => true;

  @override
  void dispose() {
    WidgetsBinding.instance.removeObserver(this);
    _tsdemoPowerEvent.cancel();

    super.dispose();
  }

  @override
  void initState() {
    super.initState();
    _isUpdateBusiness = widget.isUpdateBusiness ?? false;

    _tsdemoDetailModel = widget.tsdemoDetailModel;
    _mainTitleFocusNode = FocusNode();

    _getInitData(isInit: true);

    _controller = TextEditingController.fromValue(
      TextEditingValue(
        text: _publishDescribe ?? '',
        selection: TextSelection.fromPosition(
          TextPosition(
            affinity: TextAffinity.downstream,
            offset: _publishDescribe?.length ?? 0,
          ),
        ),
      ),
    );
    _controller.addListener(_handlerAddListener);
    _controller.text = _publishDescribe;

    _addListen();

    //请求互相关注列表（@）
    _reqUsers();
    // 请求标签
    _requestTags();
    _requestCrowd();
  }

  _handlerAddListener() {
    int extentOffset = _controller.selection.extentOffset;
    if (_publishDescribe.isNotEmpty &&
        _publishDescribe.length > extentOffset &&
        extentOffset != 0) {
      List list = getAt();
      for (var element in list) {
        if (element["userId"] != null &&
            element["userId"] != "" &&
            extentOffset > element["start"] &&
            extentOffset < element["end"]) {
          _controller.value = TextEditingValue(
            text: _publishDescribe ?? '',
            selection: TextSelection.fromPosition(
              TextPosition(
                affinity: TextAffinity.downstream,
                offset: element["end"] + 1,
              ),
            ),
          );
        }
        // if (element["userId"] != null &&
        //     element["userId"] != "" &&
        //     extentOffset == element["end"]) {
        //   String frontStr = _publishDescribe.substring(0, element["start"] - 1);
        //   String behindStr = _publishDescribe.substring(element["end"] + 1);
        //   List<String> ids = [];
        //   for (int i = 0; i < _messageAtUserIds.length; i++) {
        //     if (i != element["index"]) {
        //       ids.add(_messageAtUserIds[i]);
        //     }
        //   }
        //   _messageAtUserIds = ids;
        //   _publishDescribe = frontStr + behindStr;
        //   _controller.value = TextEditingValue(
        //     text: _publishDescribe ?? '',
        //     selection: TextSelection.fromPosition(
        //       TextPosition(
        //         affinity: TextAffinity.downstream,
        //         offset: element["start"] - 1,
        //       ),
        //     ),
        //   );
        // }
      }
      setState(() {});
    }
  }

  _getInitData({bool isInit}) {
    WishPublishManager().publishModel = PublishModel.formWishDetailModel(
      tsdemoDetailModel: _tsdemoDetailModel,
      pullCacheCompleteBlock: () {
        if (imagesChooseViewKey.currentState != null) {
          imagesChooseViewKey.currentState.updateMediasAndCover(
            _publishModel.imageChooseModels,
            _publishModel.coverImageChooseModel,
          );
        }
        _publishTitleController.text = _publishTitle;
        if (_controller != null) {
          _controller.text = _publishDescribe;
        }
      },
    );

    _publishTitleController.text = _publishTitle;
    if (_controller != null) {
      _controller.text = _publishDescribe;
    }
    if (isInit == true) {
      _requestHasAddress();
    }
  }

  /*
  @override
  void viewDidAppear(AppearBecause appearBecause) {
    super.viewDidAppear(appearBecause);
    debugPrint("内容创建页面显示了");
  }

  @override
  void viewDidDisappear(DisAppearBecause disAppearBecause) {
    super.viewDidDisappear(disAppearBecause);
    debugPrint("内容创建页面消失了");
  }
  */

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    PrimaryScrollController.of(context).addListener(_handleScrollViewEvent);
  }

  @override
  void deactivate() {
    PrimaryScrollController.of(context).removeListener(_handleScrollViewEvent);
    // _focusNode.removeListener(_handlerTextListener);

    super.deactivate();
  }

  //滚动监听取消系统键盘
  _handleScrollViewEvent() {
    cancelKeybord(context);
  }

  _addListen() {
    WidgetsBinding.instance.addObserver(this);

    _tsdemoPowerEvent =
        EventCenter.defaultCenter().on<WishPowerEvent>().listen((event) {
      setState(() {
        _publishModel.showType = event.showType;
        _publishModel.selectUsers = event.users;
      });
    });
  }

  _requestTags() {
    //先从缓存获取
    AppNetworkKit.postWithCallback(
      WishUrlPath.getTagListAll,
      cacheLevel: AppNetworkCacheLevel.one,
      completeCallBack: (ResponseModel responseModel) {
        if (responseModel.isSuccess) {
          _allTagModels.clear();
          List list = responseModel.result;
          List<Map<String, dynamic>> listMap =
              List<Map<String, dynamic>>.from(list);
          for (var element in listMap) {
            TagModel tagModel = TagModel.fromJson(element);
            _allTagModels.add(tagModel);
          }

          _publishModel.updateTagModels(_allTagModels);

          // 编辑态的时间处理
          if (_dateChooseString != null && _dateChooseString.isNotEmpty) {
            _publishModel.dateChooseBean ??= DateChooseBean();
            _publishModel.dateChooseBean.realChooseDate = _dateChooseString;
          }

          if (mounted) {
            setState(() {});
          }
        }
      },
    );
  }

  ///众筹
  _requestCrowd() {
    CrowdApi.getWishCrownConfig();
  }

  Future<bool> _requestHasAddress() async {
    // 地址秒选
    if (_addressModel == null) {
      _publishModel.addressModel =
          UserInfoManager().userModel.defaultAddressModel;
      if (mounted) {
        setState(() {});
      }
    }

    bool getSuccess = await AddressApi.getAddressList();
    if (getSuccess && _addressModel == null) {
      _publishModel.addressModel =
          UserInfoManager().userModel.defaultAddressModel;
      if (mounted) {
        setState(() {});
      }

      return true;
    } else {
      return false;
    }
  }

  @override
  Widget backgroundWidget(BuildContext context) {
    return Container(
      color: Colors.white,
    );
  }

  @override
  bool get shouldCustomOnPressed => true;

  @override
  Future<bool> customOnPressedBack() async {
    FocusScope.of(context).requestFocus(FocusNode());
    // Navigator.of(context).pop();

    if (_tsdemoId != null) {
      var result = await AlertUtil.showTwoActionAlert(
        context: context,
        title: '确定要退出编辑吗？',
        cancelTitle: '确认退出',
        okTitle: '继续编辑',
        cancelHandle: () {
          Navigator.of(context).pop(false);
        },
        okHandle: () {},
      );
      return false;
    } else {
      if (PublishCacheUtil.exsitToPublishData(_publishModel)) {
        var result = await AlertUtil.showTwoActionAlert(
          context: context,
          title: '将此次编辑保留？',
          cancelTitle: '不保留',
          okTitle: '保留',
          cancelHandle: () {
            PublishCacheUtil.clearCacheData();
            Navigator.of(context).pop();
          },
          okHandle: () {
            // LoadingUtil.showDongingTextInContext(context, '保存中');
            LoadingUtil.show();
            _publishModel.pushCacheData(context).then((value) {
              LoadingUtil.dismiss();
              // LoadingUtil.dismissDongingTextInContext(context);
              Navigator.of(context).pop();
            });
          },
        );
        return false;
      } else {
        Navigator.of(context).pop();
        return true;
      }
    }
  }

  @override
  Widget appBarWidget(BuildContext context) {
    return QuickAppBar(
      context,
      backgroundColor: Colors.transparent,
      leadingText: '取消',
      leadingTextWidth: 67.w_bj,
      customOnPressedBack: () {
        customOnPressedBack();
      },
      title: _isUpdateBusiness == true ? '编辑内容' : '创建内容',
      actions: [
        ToolBarTextActionWidget(
          width: 100.w_bj,
          text: "我的内容",
          textColor: Colors.black,
          color: Colors.transparent,
          onPressed: () {
            // 跳转到个人空间
            RouteManager.pushPage(
              context,
              RouteNames.spaceUserPage,
              arguments: {"id": UserInfoManager().userModel.id},
            );
          },
        ),
      ],
    );
  }

  _handleOnChanged(String value) {
    _publishModel.publishDescribe = value;
    if (value.isEmpty) return;
    // int baseOffset = _controller.selection.baseOffset;
    // bool a = _publishDescribe[baseOffset - 1] == "@";
    // if (_publishDescribe[baseOffset - 1] == "@") {
    //   _showRelationUserModal();
    // }
    var _regExp = r"@$"; // 以@结尾
    var _regExpValue = RegExp(_regExp).allMatches(value);
    // print('_regExpValue = ${_regExpValue}');
    if (_regExpValue.isNotEmpty) {
      // 命中正则表达式，唤起@弹窗
      if (_relationUsers.isNotEmpty &&
          (_isOpenAtDialog == null || _isOpenAtDialog == false)) {
        _isOpenAtDialog = true;
        setState(() {});
        _showRelationUserModal();
      }
    }
    setState(() {});
  }

  _showRelationUserModal() async {
    bool b = true;

    b = await showDialog<bool>(
      context: context,
      useSafeArea: false,
      builder: (context) {
        return RelationUserModal(
          onClickItem: (RelationUser user) {
            _onclickUser(user);
          },
        );
      },
    );
    _isOpenAtDialog = b;
    setState(() {});
  }

  _reqUsers() async {
    ResponseModel responseModel = await AppNetworkKit.post(
      UrlPath.pageFriendRelation,
      params: {
        'pageNum': 1,
        'pageSize': 100,
        'scene': 'at_list',
        'searchKey': '',
      },
    );
    if (responseModel.isSuccess) {
      Relation relation = Relation.fromJson(responseModel.result);
      _relationUsers = relation.resultList ?? [];
      setState(() {});
    }
  }

  _onclickUser(RelationUser item) {
    // item.avatar
    // 将选中的item.nickname 替换到当前的@
    int length = _controller.text.length;
    String atStr = '\u0020\u2061\u2061@${item.nickname}\u2061\u0020';
    _controller.text = _controller.text.substring(0, length - 1) + atStr;
    _publishModel.publishDescribe = _controller.text;
    // 先不判断是否已经从输入框删除 无脑加
    _publishModel.messageAtUserIds.add(item.userId);
    // bool existed = false;
    // if (!_messageAtUserIds.contains(item.userId)) {
    // }
    // 移动光标到最后
    _controller.selection = TextSelection.fromPosition(
      TextPosition(
        affinity: TextAffinity.downstream,
        offset: _controller.text.length,
      ),
    );

    // setState(() {});
  }

  @override
  double contentWidgetBottom(WidgetType widgetType, double screenBottomHeight) {
    return screenBottomHeight;
  }

  // 视图底部 '添加更多商品'
  @override
  Widget bottomAdsorbWidget(BuildContext context, double screenBottomHeight) {
    double buttonWidth = 166.w_bj;
    Widget addGoodsButton = ThemeBorderButton(
      width: buttonWidth,
      height: 33.h_bj,
      cornerRadius: 43.h_bj * 0.5,
      borderColorType: ThemeBGType.black,
      title: '添加商品',
      titleStyle: ButtonBoldTextStyle(fontSize: 11.h_bj),
      onPressed: () {
        return WishAddUtil.goAddGoodsSku(
          context,
          keyword: _keyword,
          tabIndex: _tabIndex,
          tsdemoTags: tsdemoTags,
          tsdemoItemModels: _showGoodsModels,
          isCrowd: _isCrowd,
          tsdemoType: _tsdemoType,
          tsdemoItemModelsValueChangeBlock: (
            bWishItemModels,
            keyword,
            tabIndex,
            isCrowd,
            crowdNum,
          ) {
            setState(() {
              _publishModel.showGoodsModels = bWishItemModels;
              _keyword = keyword;
              _tabIndex = tabIndex;
              _publishModel.isCrowd = isCrowd;
              _publishModel.crowdNum = crowdNum;
            });
            goodsChooseKey.currentState.updateCrowdInfo(
              isCrowd: _isCrowd,
              crowdNum: _crowdNum,
            );
          },
        );
      },
    );
    List<Widget> buttons = [];
    if (!_isCrowd || (_showGoodsModels != null && _showGoodsModels.isEmpty)) {
      buttons.add(addGoodsButton);
    }
    String publishButtonTitle = _isUpdateBusiness == true ? '保存' : '发布';
    publishButtonTitle += "内容";
    Widget publishButton = ThemeBGButton(
      width: buttons.isNotEmpty ? buttonWidth : buttonWidth * 2,
      height: 33.h_bj,
      cornerRadius: 43.h_bj * 0.5,
      bgColorType: ThemeBGType.theme,
      title: publishButtonTitle,
      titleStyle: ButtonBoldTextStyle(fontSize: 11.h_bj),
      onPressed: throttle(() async {
        _tryPublish();
      }),
      // onPressed: () {
      //   _tryPublish();
      // },
    );

    // if (_showGoodsModels.isNotEmpty) {

    buttons.add(publishButton);
    return AbsorbBottomContainer(
      height: (13.0 + 33.0 + 13.0).h_bj,
      childPadding: EdgeInsets.only(bottom: 15.h_bj),
      child: Container(
        child: Row(
          mainAxisAlignment: MainAxisAlignment.spaceEvenly,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: buttons,
        ),
      ),
    );
    // } else {
    //   return null;
    // }
  }

  @override
  bool resizeToAvoidBottomInset() => false; // 使得 bottomAdsorbWidget 不会被弹起来

  @override
  Widget buildSuccessWidget(BuildContext context) {
    return CustomScrollView(
      physics: const BouncingScrollPhysics(),
      controller: _customScrollcontroller,
      slivers: <Widget>[
        SliverToBoxAdapter(
          child: Container(
            padding: EdgeInsets.only(
              left: 15.w_bj,
              right: 15.w_bj,
              top: 5.h_bj,
              bottom: 39.h_bj,
            ),
            child: Column(
              children: [
                // 图片
                _imagesChooseView(context),
                // 文本
                Container(height: 20.h_bj),
                _mainTitleAndValueWidget(context),
                // 标签
                Container(height: 20.h_bj),
                _tagChooseView(context),
                // 留白
                Container(height: 24.h_bj),
                _separationLine(),
                // 录音
                // _voiceView(context),
                // _separationLine(),
                // 定位
                _locationView(context),
                _separationLine(),
                // 日期(改由从标签上设置)
                // _dateChooseBean == null
                //     ? Container()
                //     : _dateChooseView(context),
                // _dateChooseBean == null ? Container() : _separationLine(),
                // 可见范围
                _jurisdictionView(context),
                _separationLine(),
                // 地址
                _addressCell(context),
                _separationLine(),
                // 商品添加
                Container(height: 15.h_bj),
                GoodsChooseWidget(
                    key: goodsChooseKey,
                    tsdemoTags: tsdemoTags,
                    showGoodsModels: _showGoodsModels,
                    goodsModelsChangeBlock: (List<Items> bWishGoodsModels) {
                      setState(() {
                        _publishModel.showGoodsModels = bWishGoodsModels;
                      });
                    },
                    keyword: _keyword,
                    tabIndex: _tabIndex,
                    isCrowd: _isCrowd,
                    crowdNum: _crowdNum,
                    hasWishCrowd: _hasWishCrowd,
                    hasEditWishGoods: _hasEditWishGoods,
                    tsdemoType: _tsdemoType,
                    keywordCallback: (keyword, tabIndex) {
                      _keyword = keyword;
                      _tabIndex = tabIndex;
                      setState(() {});
                    },
                    isCrowdCallback: (bool b, int count) {
                      _publishModel.isCrowd = b;
                      _publishModel.crowdNum = count;
                      setState(() {});
                    },
                    crowdNumCallback: (int count) {
                      _publishModel.crowdNum = count;
                      setState(() {});
                    },
                    onKeyboardListenerCallback: (double h) {
                      _onKeyboardListenerCallback(h);
                    }),

                Container(height: 140.h_bj),
              ],
            ),
          ),
        ),
      ],
    );
  }

  _onKeyboardListenerCallback(double h) {
    _customScrollcontroller.animateTo(
      _customScrollcontroller.position.maxScrollExtent,
      duration: const Duration(milliseconds: 100),
      curve: Curves.linear,
    );
  }

  _tryPublish() async {
    _publishModel.publishTitle = _publishTitleController.text;

    if (imagesChooseViewKey.currentState == null) {
      return;
    }

    AppImageAddDeletePickListState imageListState =
        imagesChooseViewKey.currentState;

    _publishModel.imageChooseModels = imageListState.imageChooseModels;
    PickPhotoAllowType pickAllowType = imageListState.pickAllowType;
    _publishModel.coverImageChooseModel = imageListState.coverImageChooseModel;

    FocusScope.of(context).requestFocus(FocusNode());

    bool isUpdateBusiness = widget.isUpdateBusiness;
    bool canRequest = await WishPublishManager().requestPublish(
      context,
      isUpdateBusiness,
      pickAllowType,
      /*
      uploadStateProgressBlock: (uploadState, totalProgressValue) {
        if (uploadState == UploadState.uploadStart) {
          String progressPrefixText =
              pickAllowType == PickPhotoAllowType.videoOnly ? '视频' : '图片';
          ProgressUtil.showProgressHud(
            context,
            progressTextGetBlock: (double progressValue) {
              String progressText = progressValue.toStringAsFixed(2);
              return "$progressPrefixText上传中$progressText";
            },
          );
        } else if (uploadState == UploadState.uploading) {
          ProgressUtil.updateProgressValue(context, totalProgressValue);
        } else if (uploadState == UploadState.uploadFailure ||
            uploadState == UploadState.publishFailure) {
          ProgressUtil.hideProgressHud(context);
        } else if (uploadState == UploadState.publishSuccess) {
          ProgressUtil.hideProgressHud(context);
        }
      },
      publishCompleteHandle: (ResponseModel responseModel) {
        if (isUpdateBusiness) {
          ToastUtil.showMessage('保存成功');
          Navigator.pop(context);
        } else {
          AlertUtil.showCancelOKAlert(
            context: context,
            title: '清单创建成功',
            cancelTitle: '立即查看',
            okTitle: '继续创建',
            cancelHandle: () {
              // 发送通知，跳转到关注列表
              Navigator.of(context).pop();
              eventBus.fire(WishPublishSuccess()); // 发布成功，点击立即查看，进入首页-关注列表。
            },
            okHandle: () {
              // Navigator.of(context).pop();

              if (imagesChooseViewKey.currentState != null) {
                imagesChooseViewKey.currentState.clear();
              }
              setState(() {
                _tsdemoDetailModel = null;
                _getInitData(isInit: false);
              });
            },
          );
        }
      },
      */
    );

    if (canRequest == true) {
      eventBus.fire(WishPublishRequestAndGoBackEvent()); // 内容发起发布请求后返回到指定界面
      Navigator.pop(context); // 发布即退出
      return;
    }
  }

  /*
  void _addText(BuildContext context) {
    FocusScope.of(context).requestFocus(FocusNode());
    BrnBottomWritePicker.show(
      context,
      title: "编辑寄语",
      hintText: "快来说说你许下的愿望吧",
      onConfirm: (context, string) {
        Navigator.of(context).pop();
        Singleton.instance.stopPlayer();
        setState(() {
          _publishDescribe = string;
        });
        return;
      },
      onCancel: (_) {
        Navigator.of(context).pop();
        return;
      },
      defaultText: _publishDescribe,
    );
  }
  */

  Widget _separationLine({double marginTop, double marginBottom}) {
    return Container(
      height: 0.5.h_bj,
      color: const Color(0xFFE6E6E6),
      margin: EdgeInsets.only(
        top: marginTop ?? 0,
        bottom: marginBottom ?? 0,
      ),
    );
  }

  GlobalKey<AppImageAddDeletePickListState> imagesChooseViewKey = GlobalKey();

  Widget _imagesChooseView(BuildContext context) {
    double width = MediaQuery.of(context).size.width;
    // double height = MediaQuery.of(context).size.height;
    return AppImageAddDeletePickList(
      key: imagesChooseViewKey,
      // needVideoFrames: true,
      width: width - 2 * 15.w_bj,
      dragEnable: true,
      addCellType: AddCellType.image_only_default,
      imageChooseModels: _imageChooseModels,
      coverImageChooseModel: _coverImageChooseModel,
      needVideoFrames: true,
      mediasOrCoverChangeBlock: (
        List<AppImageChooseBean> imageChooseModels,
        ImageChooseBean coverImageChooseModel,
      ) {
        _publishModel.imageChooseModels = imageChooseModels;
        _publishModel.coverImageChooseModel = coverImageChooseModel;
        // setState(() {}); // 已在其内部自己实现视图更新，这里不用多此一举
      },
      downloadVideoBlock: (ImageChooseBean imageChooseModel) async {
        File video = await WishPublishManager().downloadVideo(
          context,
          imageChooseModel.networkUrl,
        );
        if (video == null) return null;
        imageChooseModel.compressVideoBean = VideoCompressBean(
            originPath: video.path,
            compressPath: video.path,
            compressInfoProcess: CompressInfoProcess.finishAll);
        return imageChooseModel;
      },
    );
  }

  Widget _mainTitleView(BuildContext context) {
    return Row(
      mainAxisSize: MainAxisSize.max,
      children: [
        // Container(width: Adapt.px(16)),
        // Image.asset(
        //   "images/hope/compile_icon1.png",
        //   width: Adapt.px(28),
        //   fit: BoxFit.fitWidth,
        // ),
        Expanded(
          child: TextField(
            controller: _publishTitleController,
            textInputAction: TextInputAction.done,
            style: TextStyle(
              color: const Color(0xff333333),
              fontSize: 16.h_bj,
              height: 1,
            ),
            maxLines: 2,
            minLines: 1,
            focusNode: _mainTitleFocusNode,
            // maxLength: 20,
            onSubmitted: (String newText) {
              print("onSubmitted newText:$newText");
              // String oldText = _publishTitle;
              // print("newText=$newText");
              // int textLength = _publishTitle.length;
              // if (textLength >= 20 && newText == oldText) {
              //   ToastUtil.showMessage("标题最多输入20字");
              // }

              // setState(() {
              //   _publishTitle = newText;
              // });
            },
            inputFormatters: <TextInputFormatter>[
              LengthLimitingTextInputFormatter(20),
            ],
            onChanged: (String newText) {
              print("onChanged newText:$newText");
              setState(() {
                String oldText = _publishTitle;
                int textLength = Characters(newText).length;
                if (textLength >= 20 && newText == oldText) {
                  ToastUtil.showMessage("title's maximum words number is 20");
                  newText = newText.substring(0, 20);
                }
                print(textLength);
                print(newText);
              });

              setState(() {
                _publishModel.publishTitle = newText;
              });
            },
            decoration: InputDecoration(
              isDense: true,
              counterText: "",
              //此处控制最大字符是否显示
              border: InputBorder.none,
              contentPadding: EdgeInsets.only(
                  // left: Adapt.px(10),
                  // right: Adapt.px(10),
                  // top: Adapt.px(12),
                  // bottom: Adapt.px(12),
                  ),
              hintText: "填写标题获得更多流量～",
              hintStyle: TextStyle(
                color: const Color(0xffBBBBBB),
                fontSize: 16.h_bj,
                height: 1,
              ),
            ),
          ),
        ),
        Column(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            Text(
              '${Characters(_publishTitle).length}/20',
              style: RegularTextStyle(fontSize: 13, color: Color(0xFF949494)),
            ),
          ],
        )
      ],
    );
  }

  List getAt() {
    var _regExp = r"(\u2061\u2061@((?!\u2061).)*\u2061)";
    var _regExpValue = RegExp(_regExp).allMatches(_publishDescribe);
    List<int> arr = [];
    List<Map<String, dynamic>> list = [];
    if (_regExpValue.isNotEmpty) {
      int index = 0;
      int lastIndex = _regExpValue.last.end;
      int i = 0;
      for (Match m in _regExpValue) {
        int startIndex = m.start;
        int endIndex = m.end;
        arr.add(startIndex);
        int i = arr.indexOf(m.start);
        list.add({
          "text": m.group(0),
          "userId": _messageAtUserIds != null &&
                  _messageAtUserIds.isNotEmpty &&
                  i < _messageAtUserIds.length &&
                  _messageAtUserIds[i] != null
              ? _messageAtUserIds[i]
              : "",
          "start": startIndex,
          "end": endIndex,
          "index": i,
        });
        ++i;
      }
    }
    return list;
  }

  //处理@名字删除
  _handlerAtOffset(String value) {
    int extentOffset = _controller.selection.extentOffset;
    int baseOffset = _controller.selection.baseOffset;
    if (_publishDescribe.isNotEmpty && _publishDescribe.length > value.length) {
      List list = getAt();
      for (var element in list) {
        if (element["userId"] != null &&
            element["userId"] != "" &&
            extentOffset == element["end"]) {
          String frontStr = _publishDescribe.substring(0, element["start"] - 1);
          String behindStr = _publishDescribe.substring(element["end"] + 1);
          List<String> ids = [];
          for (int i = 0; i < _messageAtUserIds.length; i++) {
            if (i != element["index"]) {
              ids.add(_messageAtUserIds[i]);
            }
          }
          _publishModel.messageAtUserIds = ids;
          _publishModel.publishDescribe = frontStr + behindStr;
          _controller.value = TextEditingValue(
            text: _publishDescribe ?? '',
            selection: TextSelection.fromPosition(
              TextPosition(
                affinity: TextAffinity.downstream,
                offset: element["start"] - 1,
              ),
            ),
          );
          setState(() {});
        }
      }
    }
  }

  ///TODO:①替换@文本框视图，②内容更新时候，赋值_publishDescribe，额外赋值@的id_messageAtUserIds
  ///TODO:messsge 文本框（可包含 @ 的好友）
  Widget _valueTextView(BuildContext context) {
    return LayoutBuilder(builder: (
      BuildContext context,
      BoxConstraints constraints,
    ) {
      return TextField(
          onChanged: (value) {
            _handlerAtOffset(value);
            _handleOnChanged(_controller.text);
          },
          style: TextStyle(
            fontSize: 16,
            color: BrnThemeConfigurator.instance
                .getConfig()
                .commonConfig
                .colorTextBase,
          ),
          controller: _controller,
          focusNode: _focusNode,
          maxLines: 8,
          minLines: 1,
          maxLength: 1000,
          cursorColor: BrnThemeConfigurator.instance
              .getConfig()
              .commonConfig
              .brandPrimary,
          decoration: InputDecoration(
            border: InputBorder.none,
            hintStyle: TextStyle(
                fontSize: 16,
                color: BrnThemeConfigurator.instance
                    .getConfig()
                    .commonConfig
                    .colorTextHint),
            counterStyle: TextStyle(
                fontSize: 16,
                color: BrnThemeConfigurator.instance
                    .getConfig()
                    .commonConfig
                    .colorTextHint),
            hintText: "填写寄语，让更多的人帮你实现愿望。",
          ));
      // return HideText(
      //   text: hasText == true ? _publishDescribe : "填写寄语，让更多的人帮你实现愿望。",
      //   maxWidth: constraints.maxWidth,
      //   maxLines: 5,
      //   additionText: '点击编辑',
      //   alwaysAddition: hasText,
      //   style: TextStyle(
      //     color: hasText == true
      //         ? const Color(0xFF333333)
      //         : const Color(0xFFBBBBBB),
      //     fontSize: 14.h_bj,
      //     height: 1.2,
      //   ),
      //   additionStyle: TextStyle(
      //     color: color_theme,
      //     fontSize: 14.h_bj,
      //     height: 1.2,
      //     decoration: TextDecoration.underline,
      //   ),
      // );
    });
  }

  Widget _mainTitleAndValueWidget(BuildContext context) {
    return Container(
      // color: Colors.blue,
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _mainTitleView(context),
          _separationLine(marginTop: 12.h_bj, marginBottom: 12.h_bj),
          _valueTextView(context),
        ],
      ),
    );
  }

  Widget _tagChooseView(BuildContext context) {
    return TagsWidget(
      tagModels: _allTagModels,
      tagModelsChangeBlock: (
        List<TagModel> newTagModels, {
        @required int selectTagIndex,
      }) {
        setState(() {
          _allTagModels = newTagModels;
          TagModel selectedTagModel = _allTagModels[selectTagIndex];
          _publishModel.selectedTagInfos = [
            selectedTagModel.selectedLeafTagInfo
          ];
          tsdemoTags = [selectedTagModel.selectedLeafTagInfo.id];
          setState(() {});
        });
      },
    );
  }

  /*
  Widget _voiceView(BuildContext context) {
    return VoiceChoooseCellWidget(
      leftRightPadding: leftRightPadding,
      voiceBean: _uploadVoiceBean,
      valueChangeBlock: (bVoiceBean) {
        _uploadVoiceBean = bVoiceBean;

        setState(() {});
      },
    );
  }
  */

  GlobalKey<LocationChooseCellWidgetState> _locationViewKey = GlobalKey();

  Widget _locationView(BuildContext context) {
    return LocationChooseCellWidget(
      key: _locationViewKey,
      leftRightPadding: leftRightPadding,
      locationBean: _locationBean,
      valueChangeBlock: ({bLocationBean}) {
        _publishModel.locationBean = bLocationBean;
        // if (_locationViewKey.currentState != null) {
        //   _locationViewKey.currentState.updateLocationBean(_locationBean);
        // }
        setState(() {});
      },
    );
  }

  Widget _jurisdictionView(BuildContext context) {
    String powerStr = "";
    String imageName = "";
    if (_showType == 0) {
      powerStr = "公开";
      imageName = "images/other/xx_shuijing_icon.png";
    } else if (_showType == 2) {
      powerStr = "私密";
      imageName = "images/xx_user_img.png";
    } else if (_showType == 3) {
      powerStr = "部分可见";
      imageName = "images/other/yinkaBg.png";
    } else if (_showType == 4) {
      powerStr = "不给谁看";
      imageName = "images/tsdemo/Show1.png";
    } else {
      powerStr = "公开";
      imageName = "images/tsdemo/形状.png";
    }

    /*
    return LeftImageButton(
      buttonText: text,
      buttonImageProvider:
          AssetImage(imageName.isEmpty ? "images/tsdemo/形状.png" : imageName),
      onTap: () {
        RouteManager.pushToRoute(
          context,
          PopSelectPowerPage(
            detailModel: WishDetailModel(
              showType: showType,
              showAccountInfos: _selectUsers,
            ),
          ),
        );
      },
    );
    */

    WishDetailModel detailModel = WishDetailModel(
      showType: _showType,
      showAccountInfos: _selectUsers,
    );
    // return WishDetailPowerView(
    //   powerStr: powerStr,
    //   imageName: imageName,
    //   isMe: true,
    //   detailModel: detailModel,
    // );
    // 商品
    if (true) {
      List<Items> allGoodsModels = [];
      for (var element in _showGoodsModels) {
        allGoodsModels.add(element);
      }
      for (var element in _hideGoodsModels) {
        allGoodsModels.add(element);
      }
      List<Map<String, dynamic>> allGoodsMaps = [];
      for (var element in allGoodsModels) {
        Map<String, dynamic> itemMap = {};
        itemMap["id"] = element.id;
        itemMap["state"] = element.state;
        itemMap["goodsId"] = element.id;
        itemMap["skuId"] = element.skuId;
        itemMap["num"] = element.number;
        allGoodsMaps.add(itemMap);
      }

      return AppImageTitleTextValueCell(
        leftRightPadding: leftRightPadding,
        title: "可见范围",
        imageProvider: const AssetImage(
          'assets/icon_jurisdiction.png',
          package: 'app_info_choose_kit',
        ),
        textValue: powerStr,
        textValuePlaceHodler: null,
        onTap: () {
          FocusScope.of(context).requestFocus(FocusNode());
          Navigator.of(context).push(MaterialPageRoute(builder: (context) {
            return PopSelectPowerPage(detailModel: detailModel);
          }));
        },
      );
    }
  }

  Widget _dateChooseView(BuildContext context) {
    // bool unneedDate = chooseList.isEmpty || chooseList.first.hasDate == false;
    // if (unneedDate == true) {
    //   return Container();
    // }

    String dateDescribe = _dateChooseBean?.dateDescribe;
    bool hasDateDescribe = dateDescribe != null && dateDescribe.isNotEmpty;
    dateDescribe = hasDateDescribe ? dateDescribe : '期望实现的日期';
    return ActionDateChooseCellWidget(
      title: dateDescribe,
      datePickerType: _dateChooseBean?.datePickerType,
      realChooseDateString: _dateChooseBean?.realChooseDate,
      recommendDateString: _dateChooseBean?.recommendChooseDate,
      minDateString: _dateChooseBean?.minDate,
      maxDateString: _dateChooseBean?.maxDate,
      prohibitChangeDateBlock: (errorDateType) {
        ToastUtil.showMsg("该清单不可修改日期", context);
      },
      onChooseCompleteBlock: (newDateString) {
        _publishModel.dateChooseBean.realChooseDate = newDateString;
        setState(() {});
      },
    );
  }

  // 地址
  Widget _addressCell(BuildContext context) {
    return AddressChooseCellWidget(
      leftRightPadding: leftRightPadding,
      addressModel: _addressModel,
      valueChangeBlock: ({bAddressModel}) {
        setState(() {
          _publishModel.addressModel = bAddressModel;
        });
      },
    );
  }
}
